package com.example.androidtset;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.androidtset.bean.GoodsBean;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.ArrayList;

public class AddressFragment extends Fragment {
    private MainActivity mContext;

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        mContext = (MainActivity) context;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.address_fragment, null, false);

//        mContext.setActionBarTitle("通讯录");

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        getNetData();
    }

    private void getNetData() {
        OkHttpClient okHttpClient = new OkHttpClient();

        //要有请求对象
        Request.Builder builder = new Request.Builder();

        builder.url("http://10.200.11.155:9000/goods");
        Request request = builder.build();
        Call call = okHttpClient.newCall(request);
        ((Call) call).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                Log.e("FindFragment", "onFailure: ");
            }

            @Override
            public void onResponse(Response response) throws IOException {
                String jsonStr = response.body().string();
                Gson gson = new Gson();

                TypeToken typeToken = new TypeToken<ArrayList<GoodsBean>>() {
                };
                ArrayList<GoodsBean> list = gson.fromJson(jsonStr, typeToken.getType());
                Log.e("findFragment", list.get(0).getName());
            }
        });
    }
}
